package com.hjm.project.channel.payment.controller;

import com.alibaba.fastjson.JSONObject;
import com.hjm.common.api.ls.leshua.LeShuaUtil;
import com.hjm.common.api.ls.leshua.entity.AccountAmount;
import com.hjm.common.api.ls.leshua.entity.QueryWithdraw;
import com.hjm.common.api.ls.leshua.entity.TermDto;
import com.hjm.common.api.ls.leshua.entity.TransferOrderInfo;
import com.hjm.common.utils.StringUtils;
import com.hjm.common.utils.poi.ExcelUtil;
import com.hjm.framework.aspectj.lang.annotation.Log;
import com.hjm.framework.aspectj.lang.enums.BusinessType;
import com.hjm.framework.config.CustomConfig;
import com.hjm.framework.web.controller.BaseController;
import com.hjm.framework.web.domain.AjaxResult;
import com.hjm.framework.web.page.TableDataInfo;
import com.hjm.project.channel.agent.domain.ChannelAgent;
import com.hjm.project.channel.agent.service.IChannelAgentService;
import com.hjm.project.channel.payment.domain.ChannelPayment;
import com.hjm.project.channel.payment.service.IChannelPaymentService;
import com.hjm.strategy.AgentStrategy;
import com.hjm.strategy.AgentStrategyContext;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 渠道代理商提现Controller
 *
 * @author maker-platform
 * @date 2025-03-21
 */
@Controller
@RequestMapping("/channel/payment")
public class ChannelPaymentController extends BaseController {
    private String prefix = "channel/payment";

    @Resource
    private IChannelPaymentService channelPaymentService;
    @Resource
    private IChannelAgentService channelAgentService;
    @Autowired
    private AgentStrategyContext strategyContext;

    @RequiresPermissions("channel:payment:view")
    @GetMapping()
    public String payment() {
        return prefix + "/payment";
    }

    /**
     * 查询渠道代理商提现列表
     */
    @RequiresPermissions("channel:payment:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ChannelPayment channelPayment) {
        startPage();
        List<ChannelPayment> list = channelPaymentService.selectChannelPaymentList(channelPayment);
        for (ChannelPayment payment : list) {
            String agentName = "系统代理"; // 默认值
            String baseInfo = payment.getBaseInfo();
            if (baseInfo != null && !baseInfo.trim().isEmpty()) {
                try {
                    JSONObject json = JSONObject.parseObject(baseInfo);
                    String enterpriseTitle = json.getString("enterpriseTitle");
                    String legalPersonName = json.getString("legalPersonName");
                    if (enterpriseTitle != null && !enterpriseTitle.trim().isEmpty()) {
                        agentName = enterpriseTitle;
                    } else if (legalPersonName != null && !legalPersonName.trim().isEmpty()) {
                        agentName = legalPersonName;
                    } else {
                        agentName = channelPayment.getApplyAgentId();
                    }
                } catch (Exception e) {
                    // 解析异常仍使用默认值
                    e.printStackTrace();
                }
            }
            payment.setAgentName(agentName);
        }
        return getDataTable(list);
    }

    /**
     * 导出渠道代理商提现列表
     */
    @RequiresPermissions("channel:payment:export")
    @Log(title = "渠道代理商提现", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ChannelPayment channelPayment) {
        List<ChannelPayment> list = channelPaymentService.selectChannelPaymentList(channelPayment);
        ExcelUtil<ChannelPayment> util = new ExcelUtil<ChannelPayment>(ChannelPayment.class);
        return util.exportExcel(list, "payment");
    }

    /**
     * 新增渠道代理商提现
     */
    @GetMapping("/add")
    public String add(ModelMap modelMap) {

        return prefix + "/add";
    }

    @GetMapping("/queryWithdraw/{agentId}")
    @ResponseBody
    public AjaxResult queryWithdraw(@PathVariable("agentId") String agentId) {

        ChannelAgent channelAgent = channelAgentService.selectChannelAgentByChannelAgentId(agentId);
        if (channelAgent == null) {
            return AjaxResult.error("渠道代理商为空");
        }
        AgentStrategy strategy = strategyContext.getStrategy(channelAgent.getChannelCode());
        AccountAmount amount = strategy.queryBalance(channelAgent);
        if (amount != null) {
            return AjaxResult.success(amount);
        }
        return AjaxResult.error("查询失败");
    }

    /**
     * 新增保存渠道代理商提现
     */
    @RequiresPermissions("channel:payment:add")
    @Log(title = "渠道代理商提现", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ChannelPayment channelPayment) {
        if (StringUtils.equals(channelPayment.getApplyAgentId(), CustomConfig.getAgentId()) && StringUtils.equals(channelPayment.getOperationType(), "1")) {
            return AjaxResult.error("顶级代理商不支持提现");
        }
        if (StringUtils.equals(channelPayment.getOperationType(), "2") && StringUtils.isNotEmpty(channelPayment.getDstAgentId())) {
            ChannelAgent channelAgent = channelAgentService.selectChannelAgentByChannelAgentId(channelPayment.getDstAgentId());
            if (channelAgent == null) {
                return AjaxResult.error("转账代理商不存在");
            }
            if (!StringUtils.equals(channelAgent.getChannelCode(), channelPayment.getChannelCode())) {
                return AjaxResult.error("转账代理商渠道编号不对");
            }
        }
        return toAjax(channelPaymentService.insertChannelPayment(channelPayment));
    }

    /**
     * 修改渠道代理商提现
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap) {
        ChannelPayment channelPayment = channelPaymentService.selectChannelPaymentById(id);
        mmap.put("channelPayment", channelPayment);
        return prefix + "/edit";
    }

    /**
     * 修改保存渠道代理商提现
     */
    @RequiresPermissions("channel:payment:edit")
    @Log(title = "渠道代理商提现", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ChannelPayment channelPayment) {
        return toAjax(channelPaymentService.updateChannelPayment(channelPayment));
    }

    /**
     * 删除渠道代理商提现
     */
    @RequiresPermissions("channel:payment:remove")
    @Log(title = "渠道代理商提现", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(channelPaymentService.deleteChannelPaymentByIds(ids));
    }

    /**
     * 代付查询
     */
    @Log(title = "代付查询", businessType = BusinessType.OTHER)
    @RequiresPermissions("channel:payment:queryWithdraw")
    @PostMapping("/queryWithdraw")
    @ResponseBody
    public AjaxResult queryWithdraw(Integer id) {
        ChannelPayment channelPayment = channelPaymentService.selectChannelPaymentById(id);
        if (channelPayment == null) {
            return AjaxResult.error("查询失败");
        }
        AgentStrategy strategy = strategyContext.getStrategy(channelPayment.getChannelCode());
        if (StringUtils.equals(channelPayment.getOperationType(), "1")) {
            strategy.queryWithdraw(channelPayment);
        } else {
            strategy.queryTransfer(channelPayment);
        }
        channelPaymentService.updateChannelPayment(channelPayment);
        return success();
    }
}
